use regex::Regex;

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    let re = Regex::new(r"(\d+)\((\d+)\)").expect("Invalid regex"); // 提取被转换的数字和原来的基数
    if let Some(caps) = re.captures(num_str) {
        let num = caps.get(1).map_or("", |m| m.as_str());
        let radix = caps.get(2).map_or(10, |m| m.as_str().parse::<u32>().unwrap());
        let mut base: u32 = 1;
        let mut convert_to_ten = if radix == 10 {    // 先将被转换的数字变成十进制
            num.parse::<u32>().unwrap()
        } else{
            let mut tmp: u32 = 0;
            for ch in num.chars().rev() {
                tmp += (ch.to_digit(10).unwrap() as u32) * base;
                base *= radix;
            }
            tmp
        };
        let mut result = String::new();
        while convert_to_ten > 0 {      // 将十进制数转换为目标基数，方法是先模再除
            let remainder = convert_to_ten % to_base;
            convert_to_ten /= to_base;
            if remainder < 10 {
                result.push_str(&remainder.to_string());
            } else {
                result.push((remainder - 10 + 'a' as u32) as u8 as char);
            }
        }
        result.chars().rev().collect::<String>()
    }else{
        "0".to_string()
    }
}
